package com.darksides.lenditweb.client.presenter;

import com.darksides.lenditweb.client.LenditEventBus;
import com.darksides.lenditweb.client.bean.UserBean;
import com.darksides.lenditweb.client.i18n.UserViewMessages;
import com.darksides.lenditweb.client.presenter.view_interface.IUserViewInterface;
import com.darksides.lenditweb.client.service.UserServiceAsync;
import com.darksides.lenditweb.client.util.cookie.CookieUtils;
import com.darksides.lenditweb.client.util.locale.Locale;
import com.darksides.lenditweb.client.view.UserView;
import com.darksides.lenditweb.shared.exceptions.user.EmailAlreadyUsedException;
import com.darksides.lenditweb.shared.exceptions.user.UserNotFoundException;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.HasClickHandlers;
import com.google.gwt.http.client.UrlBuilder;
import com.google.gwt.user.client.Cookies;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.Window.Location;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.Widget;
import com.google.inject.Inject;
import com.mvp4g.client.annotation.Presenter;
import com.mvp4g.client.presenter.BasePresenter;

/**
 * @author Benjamin Barbier
 *
 */
@Presenter( view = UserView.class )
public class UserPresenter extends BasePresenter<IUserViewInterface, LenditEventBus> {

	@Inject
	private UserServiceAsync userService = null;
	
	private final UserViewMessages i18n = GWT.create(UserViewMessages.class);
	
	@Override
	public void bind() {
		
		view.getCreateUserButton().addClickHandler( new ClickHandler() {
			@Override
			public void onClick( ClickEvent event ) {
				UserBean user = new UserBean();
				user.setFirstName( view.getFirstName().getText() );
				user.setLastName( view.getLastName().getText() );
				user.setEmail( view.getEmail().getText() );
				createUser( user );
			}
		} );
		view.getGetUserButton().addClickHandler( new ClickHandler() {
			@Override
			public void onClick( ClickEvent event ) {
				String userId = view.getId().getText();
				getUser(userId);
			}
		});
		((HasClickHandlers)view.getCloseDialog()).addClickHandler( new ClickHandler() {
			@Override
			public void onClick( ClickEvent event ) {
				view.getDialogBox().hide();
			}
		});
		view.getDeleteUserButton().addClickHandler(new ClickHandler() {
			@Override
			public void onClick( ClickEvent event ) {
				String userId = view.getId().getText();
				deleteUser(userId);
			}
		});
		view.getFrFlag().addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent event) {
            	changeLanguage(Locale.FRENCH);
            }
		});
		view.getEnFlag().addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent event) {
            	changeLanguage(Locale.ENGLISH);
            }
		});
		
	}

    public void changeLanguage(Locale locale) {
        Cookies.setCookie(CookieUtils.LANGUAGE_COOKIE, locale.getLanguage(), CookieUtils.getInstance().getDuration());
        UrlBuilder builder = Location.createUrlBuilder().setParameter("locale", locale.getLanguage());
        Window.Location.replace(builder.buildString());
	}
	
	private void cleanFields() {
		view.getLastName().setText("");
		view.getFirstName().setText("");
		view.getEmail().setText("");
		view.getId().setText("");
	}
	
	public void onStart() {
		cleanFields();
		eventBus.changeBody( view.getViewWidget() );
	}
	
	void createUser( UserBean user ) {
		AsyncCallback<UserBean> callback = new AsyncCallback<UserBean>() {
			public void onFailure( Throwable caught ) {
				if (caught instanceof EmailAlreadyUsedException) {
					sendPopUp(" ERROR ", new Label(i18n.exceptionEmailAlreadyUsed()));
				} else {
					sendPopUp(" ERROR ", new Label(i18n.exceptionUnknow()));
				}
			}
			public void onSuccess( UserBean user ) {
				eventBus.userCreated( user );
				cleanFields();
			}
		};
		userService.create( user, callback );
	}
	
	void getUser( String userId ) {
		AsyncCallback<UserBean> callback = new AsyncCallback<UserBean>() {
			public void onFailure( Throwable caught ) {
				if (caught instanceof UserNotFoundException) {
					sendPopUp(" ERROR ", new Label(i18n.exceptionUserNotFound()));
				} else {
					sendPopUp(" ERROR ", new Label(i18n.exceptionUnknow()));
				}
			}
			public void onSuccess( UserBean user ) {
				eventBus.userGeted( user );
				cleanFields();
			}
		};
		userService.get(userId, callback);
	}
	
	void deleteUser( String userId ) {
		AsyncCallback<UserBean> callback = new AsyncCallback<UserBean>() {
			public void onFailure( Throwable caught ) {
				if (caught instanceof UserNotFoundException) {
					sendPopUp(" ERROR ", new Label(i18n.exceptionUserNotFound()));
				} else {
					sendPopUp(" ERROR ", new Label(i18n.exceptionUnknow()));
				}
			}
			public void onSuccess( UserBean user ) {
				eventBus.userDeleted( user );
				cleanFields();
			}
		};
		userService.delete(userId, callback);
	}
	
	public void onUserCreated( UserBean user ) {
		displayUser(user, i18n.createUserTitle());
	}
	public void onUserGeted( UserBean user ) {
		displayUser(user, i18n.getUserTitle());
	}
	public void onUserDeleted( UserBean user ) {
		displayUser(user, i18n.deleteUserTitle());
	}
	
	public void displayUser( UserBean user, String title ) {
		Grid getedGrid = new Grid( 4, 2 );
		getedGrid.setText( 0, 0, i18n.id() );
		getedGrid.setText( 1, 0, i18n.firstname() );
		getedGrid.setText( 2, 0, i18n.lastname() );
		getedGrid.setText( 3, 0, i18n.email() );
		getedGrid.setText( 0, 1, user.getId() );
		getedGrid.setText( 1, 1, user.getFirstName() );
		getedGrid.setText( 2, 1, user.getLastName() );
		getedGrid.setText( 3, 1, user.getEmail() );
		sendPopUp(title, getedGrid);
	}
	
	/**
	 * Show Popup with close button.
	 * 
	 * @param title
	 * @param content
	 */
	public void sendPopUp(String title, Widget content) {
		DialogBox dialogBox = view.getDialogBox();
		dialogBox.setVisible(true);
		dialogBox.setAnimationEnabled(true);
		dialogBox.setText(title);
		dialogBox.center();
		Grid dialogGrid = new Grid(2,1);
		dialogGrid.setWidget(0, 0, content);
		dialogGrid.setWidget(1, 0, view.getCloseDialog());
		dialogBox.setWidget(dialogGrid);
	}

}
